//
//  SHHomeViewController.swift
//  ServiceHelper
//
//  Created by Stan Wu on 15/4/12.
//  Copyright (c) 2015 Stan Wu. All rights reserved.
//

import UIKit

class SHHomeViewController: UIViewController,UIGestureRecognizerDelegate,UIActionSheetDelegate {
    var aryButtons: [UIButton] = []
    var touchIndex = -1
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let imgvBG = UIImageView(image: UIImage(named: "LoginBG"))
        self.view.addSubview(imgvBG)
        
        let imgvCircle = UIImageView(image: UIImage(named: "circle"))//HomeCircleBG
        imgvCircle.center = CGPointMake(1024/2, 768/2)
        self.view.addSubview(imgvCircle)
        
        let imgvCircleBG = UIImageView(image: UIImage(named: "HomeCircleCenterBG"))
        imgvCircleBG.center = CGPointMake(1024/2, 768/2)
        self.view.addSubview(imgvCircleBG)
        
        let imgvIcon = UIImageView(image: UIImage(named: "logo"))  //HaimaIcon
        imgvIcon.center = CGPointMake(imgvCircleBG.frame.size.width/2, imgvCircleBG.frame.size.height/2)
        imgvIcon.layer.position = imgvIcon.center
        imgvIcon.layer.anchorPoint = CGPointMake(0.5, 0.5)
        imgvIcon.layer.transform = CATransform3DMakeScale(0.7, 0.7, 1)
        imgvCircleBG.addSubview(imgvIcon)
        // Do any additional setup after loading the view.
        
//        var buttonTitles = "交车服务，车型展示，维修接车，试乘试驾，事故处理，预约处理，销售政策，售后促销，内闻发布".componentsSeparatedByString("，")
//        var imageNames = "Delivery,Show,Repair,Test,Accident,Orders,Policy,Promotion,News".componentsSeparatedByString(",")
        
        var buttonTitles = "预约通知，查询预约，全部订单，等待确认".componentsSeparatedByString("，")
        var imageNames = "Notice,search,form,wait".componentsSeparatedByString(",")

        
        
        let center = CGPointMake(1024/2, 768/2)
        let radius: CGFloat = 260
        for i in 0 ..< buttonTitles.count{
            let btn: UIButton = UIButton(type: UIButtonType.Custom)
            btn.frame = CGRectMake(0, 0, 80, 72)
            let img = UIImage(named: "HomeIcon\(imageNames[i])")
            btn.setImage(UIImage(named: "HomeIcon\(imageNames[i])"), forState: .Normal)
            btn.setImage(UIImage(named: "HomeIcon\(imageNames[i])_blue"), forState: .Selected)
            btn.setTitle(buttonTitles[i], forState: .Normal)
            btn.titleLabel?.font = UIFont.boldSystemFontOfSize(16)
            btn.setTitleColor(UIColor(white: 0.49, alpha: 1), forState: .Normal)
            btn.setTitleColor(UIColor(red: 0, green: 0.7, blue: 1, alpha: 1), forState: .Selected)
            btn.titleEdgeInsets = UIEdgeInsetsMake(35.0, -img!.size.width+10, -10, 0)
            btn.imageEdgeInsets = UIEdgeInsetsMake(-35.0, buttonTitles[i].sizeWithAttributes(["NSForegroundFont":btn.titleLabel!.font]).width/2.0, 0, 0)
            
        
            let angle = M_PI*2.0/4.0*(Double(i)-0.5)+M_PI*1.5
            
            let xv = CGFloat(cos(angle))
            let yv = CGFloat(sin(angle))
            let x:CGFloat = center.x + xv*radius
            let y:CGFloat = center.y + yv*radius
            
        
            btn.center = CGPointMake(x, y)
            self.view.addSubview(btn)
            btn.tag = i
            btn.userInteractionEnabled = false
            
            aryButtons.append(btn)
        }
        
        let pan = UIPanGestureRecognizer(target: self, action:#selector(SHHomeViewController.panned(_:)))
        pan.delegate = self
        self.view.addGestureRecognizer(pan)
        
        let btn = UIButton(type: .Custom)
        btn.setImage(UIImage(named: "HomeButtonSettings"), forState: .Normal)
        btn.sizeToFit()
        btn.center = CGPointMake(1024.0-btn.frame.size.width/2.0, 768-btn.frame.size.height/2.0)
        self.view.addSubview(btn)
        btn.addTarget(self, action:#selector(SHHomeViewController.settingsClicked(_:)), forControlEvents:.TouchUpInside)
        
        
    }
    
    func settingsClicked(sender: UIButton){
        let actionSheet = UIActionSheet()
        actionSheet.title = "选择要进行的操作"
        actionSheet.delegate = self
        actionSheet.addButtonWithTitle("注销")
        actionSheet.addButtonWithTitle("取消")
//        var actionSheet = UIActionSheet(title: "选择要进行的操作", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles:nil)
//        actionSheet.addButtonWithTitle("注销")
        actionSheet.showFromRect(sender.frame, inView: self.view, animated: true)
        
    }
    
    func showOrders(){
        let vcOrders = SHOrdersViewController()
        let nav = UINavigationController(rootViewController: vcOrders)
        self.presentViewController(nav, animated: true, completion: nil)
    }
    
    func showOrdersNotification(){
//        let vcOrdersNotification = SHOrdersNotificationViewController()
//        vcOrdersNotification.strNavTitle = "预约通知"
//        let nav = UINavigationController(rootViewController: vcOrdersNotification)
//        self.presentViewController(nav, animated: true, completion: nil)
        let vcAllOrders = HMAllOrdersViewController()
        vcAllOrders.strNavTitle = "预约通知"
        vcAllOrders.isFromNotification = true
        let nav = UINavigationController(rootViewController: vcAllOrders)
        self.presentViewController(nav, animated: true, completion: nil)
       
    }
    
    func showAllOrders(){
        let vcAllOrders = HMAllOrdersViewController()
        vcAllOrders.strNavTitle = "全部订单"
        let nav = UINavigationController(rootViewController: vcAllOrders)
        self.presentViewController(nav, animated: true, completion: nil)
    }
    
    
    func searchOrders(){
//        let vcOrdersNotification = SHOrdersNotificationViewController()
//        vcOrdersNotification.strNavTitle = "查询订单"
//        let nav = UINavigationController(rootViewController: vcOrdersNotification)
//        self.presentViewController(nav, animated: true, completion: nil)
        
        let vcAllOrders = HMAllOrdersViewController()
        vcAllOrders.strNavTitle = "查询预约"
        vcAllOrders.isFromSearchOrder = true
        let nav = UINavigationController(rootViewController: vcAllOrders)
        self.presentViewController(nav, animated: true, completion: nil)
    }
    
    func waitingOrders(){
        let vcAllOrders = HMAllOrdersViewController()
        vcAllOrders.strNavTitle = "等待确认"
         vcAllOrders.isFromWaitingOrder = true
        let nav = UINavigationController(rootViewController: vcAllOrders)
        self.presentViewController(nav, animated: true, completion: nil)
    }
    
    func panned(sender: UIPanGestureRecognizer){
        let pt: CGPoint = sender.locationInView(self.view)
        let center: CGPoint = CGPointMake(1024/2, 768/2)
    
        let x = pt.x-center.x
        let y = pt.y-center.y
        
        let r: CGFloat = sqrt(x*x+y*y)
        
        
        
        var angle = Double(acos(x/r))
        if y<0 {
            angle += M_PI
        }
        
        while angle > 2.0*M_PI{
            angle -= 2.0*M_PI
        }
        
        var buttonIndex = -1
        
        for i in 0 ..< 5{
            var begin = M_PI*2.0/4.0*(Double(i)-1.0)+M_PI*1.5
            var end = M_PI*2.0/4.0*(Double(i+1)-1.0)+M_PI*1.5
            
            while begin > 2.0*M_PI{
                begin -= 2.0*M_PI
            }
            while end > 2.0*M_PI{
                end -= 2.0*M_PI
            }
            
//            if angle > begin && angle < end{
//                buttonIndex = i
//                break
//            }
            if angle > begin && angle < end{
                buttonIndex = i+1
                break
            }else if angle > begin && angle > end{
                buttonIndex = i
                break
            }else if angle < begin && angle < end && angle < begin/2.0{
                buttonIndex = 2
                break
            }else{
                buttonIndex = 3
                break
            }

        }
        
        switch sender.state{
        case .Began:
            touchIndex = buttonIndex
            for i in 0 ..< 4{
                let btn = aryButtons[i]
                btn.selected = i == buttonIndex
            }
        case .Changed:
                for i in 0 ..< 4{
                    let btn = aryButtons[i]
                    btn.selected = i == buttonIndex
                }
        case .Ended:
            if buttonIndex==touchIndex{
                buttonClicked(buttonIndex)
            }
            
        default:()
            
        }
    }
    
    func buttonClicked(index: Int){
        switch index{
           
        case 0:
            showOrdersNotification()
        case 1:
             searchOrders()
        case 2:
            showAllOrders()
        case 3:
            waitingOrders()

            
           
//        case 0:
//             print(2, terminator: "")
        default:()
        }
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func updateButtonStatus(buttonIndex: Int){
        for i in 0 ..< 4{
            let btn = aryButtons[i]
            btn.selected = i == buttonIndex
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = touches.first!

        let pt: CGPoint = touch.locationInView(self.view)
        let center: CGPoint = CGPointMake(1024/2, 768/2)
        
        let x = pt.x-center.x
        let y = pt.y-center.y
        
        let r: CGFloat = sqrt(x*x+y*y)
        
        if r<200.0 && r>312.0{
            touchesCancelled(touches, withEvent: event)
            return
        }
        
        var angle = Double(acos(x/r))
        if y<0 {
            angle += M_PI
        }
        
        while angle > 2.0*M_PI{
            angle -= 2.0*M_PI
        }
        
        var buttonIndex = -1
        
        for i in 0 ..< 5{
            var begin = M_PI*2.0/4.0*(Double(i)-1.0)+M_PI*1.5
            var end = M_PI*2.0/4.0*(Double(i+1)-1.0)+M_PI*1.5
            
            while begin > 2.0*M_PI{
                begin -= 2.0*M_PI
            }
            while end > 2.0*M_PI{
                end -= 2.0*M_PI
            }
            
            if angle > begin && angle < end{
                buttonIndex = i+1
                break
            }else if angle > begin && angle > end{
                buttonIndex = i
                break
            }else if angle < begin && angle < end && angle < begin/2.0{
                buttonIndex = 2
                break
            }else{
                buttonIndex = 3
                break
            }
        }
        
        touchIndex = buttonIndex
        updateButtonStatus(touchIndex)
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = touches.first!
        
        let pt: CGPoint = touch.locationInView(self.view)
        let center: CGPoint = CGPointMake(1024/2, 768/2)
        
        let x = pt.x-center.x
        let y = pt.y-center.y
        
        let r: CGFloat = sqrt(x*x+y*y)
        
        var angle = Double(acos(x/r))
        if y<0 {
            angle += M_PI
        }
        
        while angle > 2.0*M_PI{
            angle -= 2.0*M_PI
        }
        
        var buttonIndex = -1
        
        for i in 0 ..< 5{
            var begin = M_PI*2.0/4.0*(Double(i)-1.0)+M_PI*1.5
            var end = M_PI*2.0/4.0*(Double(i+1)-1.0)+M_PI*1.5
            
            while begin > 2.0*M_PI{
                begin -= 2.0*M_PI
            }
            while end > 2.0*M_PI{
                end -= 2.0*M_PI
            }
            
            if angle > begin && angle < end{
                buttonIndex = i+1
                break
            }else if angle > begin && angle > end{
                buttonIndex = i
                break
            }else if angle < begin && angle < end && angle < begin/2.0{
                buttonIndex = 2
                break
            }else{
                buttonIndex = 3
                break
            }
        }
        
        
        if buttonIndex==touchIndex{
            buttonClicked(touchIndex)
        }
        
        touchIndex = -1
        updateButtonStatus(touchIndex)
    }
    

    // MARK: - UIActionSheet Delegate
    func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
        
        if buttonIndex >= 0 {
            let buttonTitle = actionSheet.buttonTitleAtIndex(buttonIndex)
            if buttonTitle=="注销"{
                
                NSNotificationCenter.defaultCenter().postNotificationName("LogoutAccount", object: nil)
            }

        }
        
    }

}
